<template>
  <div class="china-map-container">
    <div class="map-controls">
      <el-button @click="clearConnections" type="warning">清除连接</el-button>
      <div class="info-text">点击两个省份进行连接</div>
    </div>

    <div ref="mapContainer" class="map-wrapper"></div>

    <div class="map-legend">
      <div class="legend-title">人口分布（万人）</div>
      <div class="legend-items">
        <div class="legend-item" v-for="(item, index) in legendData" :key="index">
          <div class="legend-color" :style="{ backgroundColor: item.color }"></div>
          <span>{{ item.label }}</span>
        </div>
      </div>
    </div>

    <div class="map-info">
      <div class="info-title">统计信息</div>
      <div class="info-content">
        <div class="info-item">
          <span class="info-label">总人口：</span>
          <span class="info-value">{{ formatNumber(totalPopulation) }} 万人</span>
        </div>
        <div class="info-item" v-if="selectedProvinces.length > 0">
          <span class="info-label">已选省份：</span>
          <span class="info-value">{{ selectedProvinces.map(p => p.name).join(', ') }}</span>
        </div>
        <div class="info-item" v-if="connections.length > 0">
          <span class="info-label">连接数：</span>
          <span class="info-value">{{ connections.length }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const mapContainer = ref(null)
let chart = null
let mapDataLoaded = false

const selectedProvinces = ref([])
const connections = ref([])
const totalPopulation = ref(0)

// 图例数据
const legendData = [
  { min: 0, max: 500, color: '#E8F4FD', label: '0-500' },
  { min: 500, max: 1000, color: '#B8E0F7', label: '500-1000' },
  { min: 1000, max: 2000, color: '#7BC2F1', label: '1000-2000' },
  { min: 2000, max: 5000, color: '#2E9EE5', label: '2000-5000' },
  { min: 5000, max: Infinity, color: '#1565C0', label: '5000+' }
]

// 省份数据
const provinceData = [
  { name: '北京', value: 2189, adcode: '110000' },
  { name: '天津', value: 1386, adcode: '120000' },
  { name: '河北', value: 7556, adcode: '130000' },
  { name: '山西', value: 3718, adcode: '140000' },
  { name: '内蒙古', value: 2520, adcode: '150000' },
  { name: '辽宁', value: 4359, adcode: '210000' },
  { name: '吉林', value: 2407, adcode: '220000' },
  { name: '黑龙江', value: 3773, adcode: '230000' },
  { name: '上海', value: 2487, adcode: '310000' },
  { name: '江苏', value: 8505, adcode: '320000' },
  { name: '浙江', value: 6540, adcode: '330000' },
  { name: '安徽', value: 6127, adcode: '340000' },
  { name: '福建', value: 4188, adcode: '350000' },
  { name: '江西', value: 4519, adcode: '360000' },
  { name: '山东', value: 10170, adcode: '370000' },
  { name: '河南', value: 9883, adcode: '410000' },
  { name: '湖北', value: 5927, adcode: '420000' },
  { name: '湖南', value: 6644, adcode: '430000' },
  { name: '广东', value: 12684, adcode: '440000' },
  { name: '广西', value: 5037, adcode: '450000' },
  { name: '海南', value: 1008, adcode: '460000' },
  { name: '重庆', value: 3205, adcode: '500000' },
  { name: '四川', value: 8375, adcode: '510000' },
  { name: '贵州', value: 3856, adcode: '520000' },
  { name: '云南', value: 4721, adcode: '530000' },
  { name: '西藏', value: 365, adcode: '540000' },
  { name: '陕西', value: 3954, adcode: '610000' },
  { name: '甘肃', value: 2502, adcode: '620000' },
  { name: '青海', value: 594, adcode: '630000' },
  { name: '宁夏', value: 728, adcode: '640000' },
  { name: '新疆', value: 2585, adcode: '650000' }
]

// 飞机SVG图标
const airplaneIcon = 'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z'

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString()
}

// 加载地图数据
const loadMapData = async () => {
  try {
    const response = await fetch('/china.json')
    const data = await response.json()
    echarts.registerMap('china', data)
    mapDataLoaded = true
    console.log('地图数据加载成功')
    initMap()
  } catch (error) {
    console.error('加载地图数据失败，使用备用方案:', error)
    mapDataLoaded = false
    initMap()
  }
}

// 初始化地图
const initMap = () => {
  if (!mapContainer.value) return

  chart = echarts.init(mapContainer.value)
  updateMapData()

  window.addEventListener('resize', handleResize)
}

// 更新地图数据
const updateMapData = () => {
  if (!chart) return

  totalPopulation.value = provinceData.reduce((sum, item) => sum + item.value, 0)

  if (mapDataLoaded) {
    // 使用真实地图模式
    updateRealMap()
  } else {
    // 使用备用散点图模式
    updateScatterMap()
  }
}

// 真实地图模式
const updateRealMap = () => {
  const option = {
    backgroundColor: '#F0F8FF',
    title: {
      text: '中国人口分布地图 - 点击省份进行连接',
      left: 'center',
      top: 20,
      textStyle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#1565C0'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        if (params.seriesType === 'map') {
          return `${params.name}<br/>人口：${formatNumber(params.value)} 万人<br/>点击选择进行连接`
        }
        return `${params.name}`
      }
    },
    visualMap: {
      type: 'piecewise',
      pieces: legendData.map(item => ({
        min: item.min,
        max: item.max === Infinity ? null : item.max,
        label: item.label,
        color: item.color
      })),
      orient: 'vertical',
      right: 20,
      bottom: 50,
      textStyle: {
        color: '#333',
        fontWeight: 'bold'
      }
    },
    geo: {
      map: 'china',
      roam: true,
      zoom: 1.2,
      itemStyle: {
        areaColor: '#E8F4FD',
        borderColor: '#fff',
        borderWidth: 1.5
      },
      emphasis: {
        itemStyle: {
          areaColor: '#7BC2F1'
        }
      }
    },
    series: []
  }

  // 添加地图数据
  option.series.push({
    name: '人口分布',
    type: 'map',
    map: 'china',
    roam: true,
    zoom: 1.2,
    label: {
      show: true,
      fontSize: 10,
      color: '#333',
      fontWeight: 'bold'
    },
    emphasis: {
      label: {
        fontSize: 12,
        color: '#fff',
        fontWeight: 'bold'
      },
      itemStyle: {
        areaColor: '#FF6B35'
      }
    },
    data: provinceData.map(item => ({
      name: item.name,
      value: item.value
    })),
    itemStyle: {
      borderColor: '#fff',
      borderWidth: 1.5
    }
  })

  // 添加连接线
  connections.value.forEach((conn, index) => {
    console.log(`添加连接线 ${index}:`, conn.from.name, '->', conn.to.name)
    option.series.push({
      name: `连接线${index}`,
      type: 'lines',
      coordinateSystem: 'geo',
      zlevel: 10,
      effect: {
        show: true,
        period: 6,
        trailLength: 0.7,
        color: '#FF6B35',
        symbolSize: 12,
        symbol: airplaneIcon
      },
      lineStyle: {
        width: 4,
        opacity: 0.9,
        curveness: 0.2,
        color: '#FF6B35'
      },
      data: [{
        coords: [
          getProvinceCoords(conn.from.name),
          getProvinceCoords(conn.to.name)
        ],
        fromName: conn.from.name,
        toName: conn.to.name
      }]
    })
  })

  // 添加选中省份标记
  if (selectedProvinces.value.length > 0) {
    option.series.push({
      name: '选中省份',
      type: 'scatter',
      coordinateSystem: 'geo',
      symbolSize: 25,
      itemStyle: {
        color: '#FF6B35',
        borderColor: '#fff',
        borderWidth: 4
      },
      zlevel: 15,
      data: selectedProvinces.value.map(p => {
        const coords = getProvinceCoords(p.name)
        return {
          name: p.name,
          value: [...coords, p.value]
        }
      })
    })
  }

  chart.setOption(option)

  // 点击事件
  chart.off('click')
  chart.on('click', (params) => {
    if (params.seriesType === 'map' && params.data) {
      handleProvinceClick(params.data)
    }
  })
}

// 散点图模式
const updateScatterMap = () => {
  const series = [
    {
      name: '人口分布',
      type: 'scatter',
      symbolSize: (data) => {
        return Math.sqrt(data[2]) / 4 + 8
      },
      itemStyle: {
        color: (params) => {
          const value = params.data[2]
          if (value > 5000) return '#1565C0'
          if (value > 2000) return '#2E9EE5'
          if (value > 1000) return '#7BC2F1'
          if (value > 500) return '#B8E0F7'
          return '#E8F4FD'
        },
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        position: 'top',
        formatter: (params) => {
          return `${params.data[3]}\n${params.data[2]}万人`
        },
        fontSize: 10,
        color: '#333',
        fontWeight: 'bold'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 15,
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          borderColor: '#FF6B35',
          borderWidth: 3
        }
      },
      data: provinceData.map(item => [
        getProvinceCoords(item.name)[0],
        getProvinceCoords(item.name)[1],
        item.value,
        item.name
      ])
    }
  ]

  // 添加连接线（散点图模式）
  connections.value.forEach((conn, index) => {
    series.push({
      name: `连接线${index}`,
      type: 'lines',
      coordinateSystem: 'cartesian2d',
      zlevel: 2,
      effect: {
        show: true,
        period: 6,
        trailLength: 0.7,
        color: '#FF6B35',
        symbolSize: 10,
        symbol: airplaneIcon
      },
      lineStyle: {
        width: 3,
        opacity: 0.8,
        curveness: 0.2,
        color: '#FF6B35'
      },
      data: [{
        coords: [
          getProvinceCoords(conn.from.name),
          getProvinceCoords(conn.to.name)
        ]
      }]
    })
  })

  const option = {
    backgroundColor: '#F0F8FF',
    title: {
      text: '中国人口分布地图 - 点击省份进行连接',
      left: 'center',
      top: 20,
      textStyle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#1565C0'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        if (params.seriesType === 'scatter' && params.data) {
          return `${params.data[3]}<br/>人口：${formatNumber(params.data[2])} 万人<br/>点击选择进行连接`
        }
        return `${params.name}`
      }
    },
    xAxis: {
      type: 'value',
      show: false,
      min: 70,
      max: 140
    },
    yAxis: {
      type: 'value',
      show: false,
      min: 15,
      max: 55
    },
    series: series
  }

  chart.setOption(option)

  chart.off('click')
  chart.on('click', (params) => {
    if (params.seriesType === 'scatter' && params.data && params.data[3]) {
      handleProvinceClick({
        name: params.data[3],
        value: params.data[2]
      })
    }
  })
}

// 获取省份坐标
const getProvinceCoords = (name) => {
  const coords = {
    '北京': [116.4, 39.9],
    '天津': [117.2, 39.1],
    '河北': [114.5, 38.0],
    '山西': [112.5, 37.8],
    '内蒙古': [111.7, 40.8],
    '辽宁': [123.4, 41.8],
    '吉林': [125.3, 43.8],
    '黑龙江': [126.6, 45.7],
    '上海': [121.4, 31.2],
    '江苏': [118.7, 32.0],
    '浙江': [120.1, 30.2],
    '安徽': [117.2, 31.8],
    '福建': [119.3, 26.0],
    '江西': [115.8, 28.6],
    '山东': [117.0, 36.6],
    '河南': [113.6, 34.7],
    '湖北': [114.3, 30.5],
    '湖南': [112.9, 28.2],
    '广东': [113.2, 23.1],
    '广西': [108.3, 22.8],
    '海南': [110.3, 20.0],
    '重庆': [106.5, 29.5],
    '四川': [104.0, 30.6],
    '贵州': [106.7, 26.5],
    '云南': [102.7, 25.0],
    '西藏': [91.1, 29.6],
    '陕西': [108.9, 34.2],
    '甘肃': [103.8, 36.0],
    '青海': [101.7, 36.6],
    '宁夏': [106.2, 38.4],
    '新疆': [87.6, 43.8]
  }
  return coords[name] || [110, 35]
}

// 处理省份点击
const handleProvinceClick = (provinceData) => {
  console.log('点击省份:', provinceData.name)

  // 查找省份对象
  const province = provinceData.find ?
    provinceData.find(p => p.name === provinceData.name) :
    provinceData

  if (!province) return

  // 检查是否已选中
  const existingIndex = selectedProvinces.value.findIndex(p => p.name === province.name)

  if (existingIndex !== -1) {
    // 取消选中
    selectedProvinces.value.splice(existingIndex, 1)
    console.log('取消选中:', province.name)
  } else {
    // 添加到选中列表
    selectedProvinces.value.push(province)
    console.log('选中:', province.name, '当前选中数量:', selectedProvinces.value.length)

    // 如果有两个选中省份，创建连接
    if (selectedProvinces.value.length === 2) {
      createConnection(selectedProvinces.value[0], selectedProvinces.value[1])
    }
  }

  updateMapData()
}

// 创建连接
const createConnection = (province1, province2) => {
  console.log('创建连接:', province1.name, '->', province2.name)

  connections.value.push({
    from: province1,
    to: province2
  })

  // 清空选中省份
  selectedProvinces.value = []

  updateMapData()
}

// 清除连接
const clearConnections = () => {
  connections.value = []
  selectedProvinces.value = []
  updateMapData()
}

// 处理窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

// 组件挂载时初始化
onMounted(() => {
  loadMapData()
})

// 组件卸载前清理
onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.china-map-container {
  width: 100%;
  height: 100vh;
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
}

.china-map-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(circle at 20% 50%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 80% 80%, rgba(255, 182, 193, 0.3) 0%, transparent 50%);
  pointer-events: none;
}

.map-controls {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 15px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 15px 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.info-text {
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.map-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 1;
}

.map-legend {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  z-index: 1000;
  min-width: 180px;
}

.legend-title {
  font-weight: bold;
  margin-bottom: 15px;
  color: #1565C0;
  font-size: 14px;
}

.legend-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 12px;
  font-weight: 500;
}

.legend-color {
  width: 24px;
  height: 14px;
  border-radius: 3px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.map-info {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  z-index: 1000;
  min-width: 240px;
}

.info-title {
  font-weight: bold;
  margin-bottom: 15px;
  color: #1565C0;
  font-size: 14px;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  color: #666;
  font-size: 13px;
  font-weight: 500;
}

.info-value {
  color: #1565C0;
  font-weight: bold;
  font-size: 13px;
  text-align: right;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>